#353 – Binding a Three-State CheckBox to a Nullable Bool
July 29, 2011 2 Comments
Because a three-state CheckBox can take on any one of three different values, its current value can’t be represented by a simple bool. A bool can only take on true and false values.
A three-state CheckBox can instead be bound to a nullable bool (represented by bool?), which can take on three different values.
- true (checked)
- false (not checked)
- null (indeterminate)
In the example below, we bind a CheckBox control’s IsChecked property to a nullable bool property.
<CheckBox Content="Happy" IsChecked="{Binding IsHappy}" IsThreeState="True"/>
In the code-behind, we define the property and set the main window’s data context.
// Nullable bool - can be true, false or null public bool? IsHappy { get; set; } public MainWindow() { this.InitializeComponent(); this.DataContext = this; }
Pingback: #852 – Setting a Three-State CheckBox to an Indeterminate Value | 2,000 Things You Should Know About WPF
Sean, when I see your photo on the side of the article I know I have found my answer already. : )